﻿using Helper;
using HZY.Framework.DependencyInjection;
using Mapster;
using Model.Entity;
using Model.EntityInfo;

namespace DAL.Service
{
    public class RouteService : BaseService<RouteEntity>, IScopedSelfDependency 
    {
        public async Task<BaseResult<List<RouteInfoModel>>> GetAllRoute()
        {
            List<RouteEntity> routes = await DB.SqlSugarClient.Queryable<RouteEntity>().ToListAsync();
            List<RouteInfoModel> routeInfoModels = BuildTree(routes);
            return new BaseResult<List<RouteInfoModel>>()
            {
                Code = SystemEnums.ResCode.Success,
                Data = routeInfoModels,
                Msg = string.Empty
            };
        }

        public List<RouteInfoModel> BuildTree(List<RouteEntity> nodes)
        {
            // 使用字典存储节点，以便快速查找
            List<RouteInfoModel> _nodes = nodes.Adapt<List<RouteInfoModel>>();
            var nodeMap = _nodes.ToDictionary(node => node.Id);
            var tree = new List<RouteInfoModel>();

            foreach (var node in _nodes)
            {
                // 如果是根节点（Pid=0），添加到树的根列表
                if (node.ParentId == 0)
                {
                    tree.Add(node);
                }
                else if (nodeMap.TryGetValue(node.ParentId, out var parent))
                {
                    // 否则添加到父节点的子列表
                    parent.Children.Add(node);
                }
            }

            return tree;
        }
    }
}
